import React from 'react';
import {connect} from "dva";
import {AnyAction, Dispatch} from "redux";
import { Cascader } from 'antd';
import {CascaderOptionType} from "antd/lib/cascader";
import {ConnectState} from "@/models/connect";
import { OptionType } from '@/types/common';

interface Props{
  style?:any;
  value?: (string | number)[];
  onChange?:(value:(string | number)[])=>void;
}

interface State{
  value?: (string | number)[];
}

interface CustomCascaderProps{
  style:any;
  value: (string | number)[];
  onChange?:(value:(string | number)[])=>void;
  dispatch: Dispatch<AnyAction>;
  list:OptionType[];
}


class CustomCascader extends React.Component<CustomCascaderProps,{}> {

  componentDidMount(): void {
    this.props.dispatch({
      type: 'region/queryProvince',
    });
  }

  loadData=(selectedOptions?: CascaderOptionType[])=>{
    if (selectedOptions&&selectedOptions.length === 1) {
      this.props.dispatch({
        type: 'region/queryCity',
        payload: selectedOptions.map(item=>item.id),
      });
    } else if (selectedOptions&&selectedOptions.length === 2) {
      this.props.dispatch({
        type: 'region/queryDistrict',
        payload: selectedOptions.map(item=>item.id),
      });
    }
  };

  onChange=(value: (string | number)[], selectedOptions?: CascaderOptionType[])=>{
    const { onChange } = this.props;
    onChange&&onChange(value);
  };


  render() {
    const { value,list,style } = this.props;

    return (
      <Cascader
        options={list}
        placeholder="请选择"
        changeOnSelect={true}
        loadData={this.loadData}
        onChange={this.onChange}
        style={{width:'100%',...style}}
        value={value}
        fieldNames={{
          label:'name',
          value:'id',
          children:'children',
        }}
      />
    );
  }
}

const WrapperCascader=connect(({region}:ConnectState) => ({
  list:region.list,
}))(CustomCascader);

export default class RegionCascader extends React.Component<Props,State> {

  state={
    value:this.props.value||[]
  };

  static getDerivedStateFromProps(nextProps: Props) {
    if ('value' in nextProps) {
      return { value: nextProps.value || [] };
    }
    return null;
  }

  onChange=(value: (string | number)[])=>{
    if (!('value' in this.props)) {
      this.setState({ value });
    }
    const { onChange } = this.props;
    if (onChange) {
      onChange(value);
    }
  };


  render() {
    const { style } = this.props;
    const { value } = this.state;
    return (
      <WrapperCascader
        onChange={this.onChange}
        value={value}
        style={style}
      />
    );
  }
}



